<script setup lang="ts">
import { onMounted, reactive, ref, computed } from "vue";
import { useMessage, NLayout, NLayoutHeader, NLayoutContent, NButton, NRadioGroup, NRadioButton, NInputNumber, NFormItem, NH2, NH3, NP, NSpace, NImage } from "naive-ui";
import router from "../router";
import statusCode from "../api/statusCode";
import type { ProductInfo } from '../api/goods';
import { queryGoodsInfo } from "../api/goods";
import { addItemToCart } from "../util/cart";

const message = useMessage();

const storeIdRef = computed(() =>
  typeof router.currentRoute.value.params.storeId == 'string' ?
  +router.currentRoute.value.params.storeId :
  +router.currentRoute.value.params.storeId[0]
);

const productIdRef = computed(() =>
  typeof router.currentRoute.value.params.productId == 'string' ?
  +router.currentRoute.value.params.productId :
  +router.currentRoute.value.params.productId[0]
);


const queryInfo = async () => {
  try {
    const resp = await queryGoodsInfo(productIdRef.value);

    if (resp.status === statusCode.SUCCESS) {
      return resp.data;
    } else if (resp.status === statusCode.NO_SUCH_GOODS) {
      throw new Error(`找不到id为${productIdRef.value}的产品`);
    } else {
      throw new Error(`错误码 ${resp.status}`);
    }
  } catch (error) {
    message.error("" + error);
    return {
      productId: productIdRef,
      productName: '',
      storeId: storeIdRef.value,
      storeName: '',
      info: []
    };
  }
};

const productInfo = reactive<ProductInfo>({
  productId: productIdRef.value,
  productName: '',
  storeId: storeIdRef.value,
  storeName: '',
  info: []
});

const getProductInfo = async () => {
  const info = await queryInfo();

  Object.assign(productInfo, info);
};

onMounted(async () => {
  await getProductInfo();
});

const availableAttrs = computed(() => productInfo.info);
const chosenId = ref(-1);
const chosenAttr = computed(() =>
  productInfo.info
    .find(attr => attr.attributeId == chosenId.value)
);

const quantity = ref(0);

const handleAddToCart = () => {
  if (chosenAttr.value === undefined) {
    message.error('请先选择颜色');
    return;
  }
  if (quantity.value == 0) {
    message.error('商品件数为0');
    return;
  }
  addItemToCart({
    storeId: storeIdRef.value,
    productId: productIdRef.value,
    attributeId: chosenAttr.value.attributeId,
    quantity: quantity.value
  });
  message.success('已添加到购物车');
};

const handleRadioUpdate = () => {
  quantity.value = 0; // reset quantity after radio group updates
};

const currentImg = computed(() => chosenAttr.value?.imgPath ?? undefined);
</script>

<template>
  <n-space justify="center">
    <n-image
      v-if="currentImg"
      width="300"
      :src="currentImg"
    />
    <n-layout>
      <n-layout-header>
        <n-h2>
          店铺
          <router-link :to="{ name: 'store', params: { storeId: productInfo.storeId }}">
            {{ productInfo.storeName }}
          </router-link>
        </n-h2>
      </n-layout-header>
      <n-layout-content>
        <n-space vertical>
          <n-h3 strong>
            {{ productInfo.productName }}
          </n-h3>
          <n-form-item
            label="颜色"
            v-if="availableAttrs.length > 0"
          >
            <n-radio-group
              name="attributeId"
              v-model:value="chosenId"
              @update-value="handleRadioUpdate"
            >
              <n-radio-button
                v-for="attr of availableAttrs"
                :key="attr.attributeId"
                :value="attr.attributeId"
                :disabled="attr.stock == 0"
              >
                {{ attr.color }}
              </n-radio-button>
            </n-radio-group>
          </n-form-item>
          
          <n-p
            v-if="chosenAttr"
            depth="2"
          >
            当前库存 {{ chosenAttr.stock }}
          </n-p>
          <n-form-item label="件数">
            <n-input-number
              v-model:value="quantity"
              :min="0"
              :max="chosenAttr?.stock"
              :disabled="chosenAttr === undefined || chosenAttr.stock == 0"
            >
              <template #suffix>
                件
              </template>
            </n-input-number>
          </n-form-item>
    
          <n-form-item>
            <n-button
              type="primary"
              @click="handleAddToCart"
              :disabled="quantity == 0"
            >
              加入购物车
            </n-button>
          </n-form-item>
        </n-space>
      </n-layout-content>
    </n-layout>
  </n-space>
</template>

<style scoped>
</style>
